<?php
	include("admin-commons.php");

	$user = $_COOKIE['user'];
	$hash = $_COOKIE['hash'];
	if(strlen($user) == 0) {
		echo "<html>\n";
		echo "<h2>You must be logged in to view this page, you have been reported.</h2>\n";
		echo "</html>\n";
		die();
	}	
	
	/* Begin Page */
	pageHeader();
	adminNavigation();
	contentHeader();
	echo "<h2> Account Management </h2></br>\n";
	$createUser = $_POST['user'];
	$passwordOne = $_POST['passwordOne'];
	$passwordTwo = $_POST['passwordTwo'];
	createAccount($createUser, $passwordOne, $passwordTwo);
	contentFooter("You are logged in as ".$user);
	
	/* FUNKtions */
	
	function createAccount($createUser, $passwordOne, $passwordTwo) {
		if (strlen($createUser) == 0 || strlen($passwordOne) == 0 || strlen($passwordTwo) == 0) {
			echo "</br><b>Create a New Account</b> </br> </br>";
			echo "<form action=\"accounts.php\" method=\"post\">\n";
			echo "Username:";
			echo "</br><input type=\"text\" name=\"user\"/>";
			echo "</br>Password:";
			echo "</br><input type=\"password\" name=\"passwordOne\"/>";
			echo "</br>Confirm Password:";
			echo "</br><input type=\"password\" name=\"passwordTwo\"/>";
			echo "</br></br><input type=\"submit\" value=\"Create Account\"/>";
			echo "</form></br>\n";
		} else {
			$hash = md5($passwordOne);
			$sqlConnection = connectToDatabase();
			mysql_select_db("hpberry", $sqlConnection);
			if ($hash == md5($passwordTwo))
			{
				$safeUser = mysql_real_escape_string($createUser);
				$createUserQuery = 'INSERT INTO accounts (user, password) VALUES ("'.$safeUser.'", "'.$hash.'")';
				if(mysql_query($createUserQuery, $sqlConnection))
					echo "</br> > Successfully created new user: ".$createUser."</br></br>\n";
				else
					echo "</br> > SQL Error: ".mysql_error()."</br>\n";
			} else {
				echo "</br> > <b>PEBKAC Error:</b> Passwords did not match, please try again.</br>\n";
			}
			mysql_close($sqlConnection);
		}
	}
	
?>